﻿using LoveEatRabbit.API.Write.Applications.Commands.Roles;
using LoveEatRabbit.Domain.RBAC;
using LoveEatRabbit.ErrorCode;
using LoveEatRabbit.Infrastructure.Interfaces;
using MediatR;
using NLog.Web.LayoutRenderers;
using System.Data;

namespace LoveEatRabbit.API.Write.Applications.CommandHandlers.Roles
{
    public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, APIResult<int>>
    {
        private readonly IBaseRespository<RoleModel> roleRep;
        private readonly IBaseRespository<RolePermissionModel> roleperRep;

        public UpdateRoleCommandHandler(IBaseRespository<RoleModel> roleRep,
            IBaseRespository<RolePermissionModel> roleperRep)
        {
            this.roleRep = roleRep;
            this.roleperRep = roleperRep;
        }
        public async Task<APIResult<int>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result=new APIResult<int>();
            result.Code=APIResultCode.修改成功;
            result.Message=APIResultCode.修改成功.ToString();

            var res=roleRep.GetAll().FirstOrDefault(x=>x.RoleId==request.RoleId);
            res.RoleName=request.RoleName;
            await roleRep.UpdateAsync(res);

            var list = new List<RolePermissionModel>();
            foreach (var item in request.PermissionId)
            {
                list.Add(new RolePermissionModel()
                {
                    RoleId = res.RoleId,
                    PermissionId = item
                });
            }
            await roleperRep.UpdateRangeAsync(list);






            return await Task.FromResult(result);
        }
    }
}
